<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      border: 1px solid #333;
      cursor: url("images/pen.cur") 10 10, auto;
    }
  </style>
</head>

<body>
  <canvas width="300" height="200"></canvas>
  <p>
    <button class="clear">清除</button>
    <button class="save">保存</button>
  </p>
  <script>
    let canvas = document.querySelector("canvas")
    let ctx = canvas.getContext("2d")

    let lastX = 0, lastY = 0;
    let tag = false;    //true 可以绘制；false 不可以绘制
    //鼠标落下
    canvas.addEventListener("mousedown", (e) => {
      tag = true
      // console.log(else)
      lastX = e.offsetX;
      lastY = e.offsetY

    })


    //鼠标移动
    canvas.addEventListener("mousemove", (e) => {
      if (!tag) return
      ctx.moveTo(lastX, lastY)
      ctx.lineTo(e.offsetX, e.offsetY)
      ctx.stroke()
      lastX = e.offsetX
      lastY = e.offsetY

    })

    //鼠标抬起
    canvas.addEventListener("mouseup", (e) => {
      tag = false
    })

    //清除
    document.querySelector(".clear").addEventListener("click", () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
    })

    document.querySelector(".save").addEventListener("click", () => {
      // ctx.clearRect(0, 0, canvas.width, canvas.height)
      let result = canvas.toDataURL()
      console.log(result)
    })

  </script>

</body>

</html>